package com.wow.wa.bill.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;

public class VoConvertComponentImpl implements VoConvertComponent {

	private static final String TAG = "VoConvertComponentImpl";
	private static JCommonComent jCommonComent;

	public VoConvertComponentImpl() {
		jCommonComent = new JCommonComentImpl();
	}

	@Override
	public ContentValues contentValueFromVo(Object obj) throws Exception {

		JCommonComent comnet = new JCommonComentImpl();
		List<String> names = comnet.getAllFieldsByReflect(obj.getClass());

		ContentValues values = new ContentValues();

		for (String name : names) {
			if ("_id".equals(name)) {
				continue;
			}
			final Object str = this.getValueByFiledName(obj, name);

			values.put(name, (String) str);

		}

		return values;
	}

	private Object getValueByFiledName(Object obj, String name)
			throws Exception {
		Field f = obj.getClass().getDeclaredField(name);
		f.setAccessible(true);
		Object out = f.get(obj);
		f.setAccessible(false);
		return out;
	}

	@Override
	public <T> T convert2Bean(Object jsonVo, Class<T> tarClass)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	public <T1> List<T1> getObjForm(Cursor cursor, Class<T1> tarClass) {

		List<T1> lits = new ArrayList<T1>();
		try {

			while (cursor.moveToNext()) {
				final List<String> fieldsNames = jCommonComent
						.getAllFieldsByReflect(tarClass);
				T1 ob = tarClass.newInstance();
				for (String name : fieldsNames) {
					Log.v(TAG, "name=" + name);
					Field f = ob.getClass().getDeclaredField(name);
					f.setAccessible(true);
					int idext = cursor.getColumnIndex(name);
					Log.v(TAG, "idext=" + idext);

					if (StringUtils.equals(name, "_id")) {

						int value = cursor.getInt(idext);
						f.set(ob, value);
					} else {

						f.set(ob, cursor.getString(idext));

					}
					f.setAccessible(false);

				}
				lits.add(ob);

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return lits;

	}

}
